<?php
namespace App\Modules\Admin\Services;

use App\Models\Admin\SysPermission;
use Illuminate\Support\Str;

class PermissionService extends AdminService
{
    protected $model = SysPermission::class;

    public function getQueryBuilder(Array $data)
    {
        $this->queryBuilder = SysPermission::query();
        if(isset($data['name']) && strlen($data['name']) > 0) {
            $this->queryBuilder->where('name', $data['name']);
        }

        if(isset($data['sortBy']) && isset($data['order']) && in_array(Str::lower($data['order']), ['asc', 'desc'])) {
            $this->queryBuilder->orderBy($data['sortBy'], $data['order']);
        } else {
            $this->queryBuilder->orderBy('id', 'desc');
        }
    }

    public function routes()
    {
        $permissions = SysPermission::whereNull('perm')->get();
        return $this->formatMenuData($permissions);
    }

    private function formatMenuData($permissions, $parentId = 0)
    {
        $formatted = [];

        foreach ($permissions as $permission) {
            if ($permission->parent_id == $parentId) {
                $item = [
                    'path' => $permission->path,
                    'component' => $permission->component,
                    'name' => $permission->name,
                    'redirect' => $permission->redirect,
                    'meta' => [
                        'title' => $permission->name,
                        'icon' => $permission->icon,
                        'hidden' => $permission->visible === 0,
                        'roles' => $permission->roles->pluck('code')->flatten(),  // 你可能需要从数据库中获取相应的角色信息
                        'keepAlive' => $permission->keep_alive
                    ],
                ];

                // 递归获取子菜单
                $children = $this->formatMenuData($permissions, $permission->id);
                if (!empty($children)) {
                    $item['children'] = $children;
                }

                $formatted[] = $item;
            }
        }

        return $formatted;
    }

    public function options()
    {
        return SysPermission::where('parent_id', 0)->with('children')->get();
    }
}